package com.example.security.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.http.HeaderHttpSessionIdResolver;
import org.springframework.session.web.http.HttpSessionIdResolver;

/**
 * 会话配置类
 * 使用Redis存储会话信息
 */
@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600)  // 会话过期时间1小时
@RequiredArgsConstructor
public class SessionConfig {

    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 配置会话ID解析器
     * 使用请求头中的X-Auth-Token作为会话标识
     */
    @Bean
    public HttpSessionIdResolver httpSessionIdResolver() {
        return HeaderHttpSessionIdResolver.xAuthToken();
    }
    
    /**
     * 踢出指定用户
     * 清除用户的会话信息
     */
    public void kickoutUser(String username) {
        String pattern = "spring:session:sessions:*";
        redisTemplate.keys(pattern).forEach(key -> {
            Object value = redisTemplate.opsForHash().get(key, "sessionAttr:username");
            if (username.equals(value)) {
                redisTemplate.delete(key);
            }
        });
    }
    
    /**
     * 获取在线用户数
     */
    public long getOnlineUserCount() {
        String pattern = "spring:session:sessions:*";
        return redisTemplate.keys(pattern).size();
    }
} 